﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using CommonLibrary.Exceptions;
using CommonLibrary.Models.Configurations;
using ConnectionManager.Models;

namespace ConnectionManager.Helpers
{
    public static class SerialConnectionHelper
    {
        public static void OpenComPort(SerialPort comPort, SerialPortConfig config)
        {
            // If the port is open, close it.
            if (comPort.IsOpen) return;
            else
            {
                ConfigurePortSettings(comPort, config);
                try
                {
                    comPort.Open();
                }
                catch (Exception ex)
                {
                    throw new SimpleSmartException(ex);
                }
            }
        }

        public static void CloseComPort(SerialPort comPort)
        {
            if (!comPort.IsOpen) return;

            comPort.Close();
            comPort.Dispose();
        }

        private static void ConfigurePortSettings(SerialPort comPort, SerialPortConfig config)
        {
            // Set the port's settings
            comPort.BaudRate = config.BaudRate;
            comPort.DataBits = config.DataBits;
            comPort.StopBits = config.StopBits;
            comPort.Parity = config.Parirty;
            comPort.PortName = config.PortName;
            comPort.ReadTimeout = config.ReadTimeOut;
            comPort.WriteTimeout = config.WriteTimeOut;
        }

        public static void SendData(SerialPort comPort, PS3SerialReport dataReport)
        {
            var bytez = ByteOperationHelpers.StructureToByteArray(dataReport);
            comPort.Write(bytez, 0, bytez.Length);
        }

        public static List<string> GetComPortList()
        {
            return SerialPort.GetPortNames().ToList();
        }
    }
}

